/*年轻人，只管向前看，不要管自暴自弃者的话*/
import 'package:device_info_plus/device_info_plus.dart';
import 'package:get/get.dart';
import 'dart:io';

import '../constant/sp_key.dart';
import '../net/http_url.dart';
import '../routes/router.dart';
import '../util/sputil.dart';

///create by itz on 2024/1/9 11:41
///desc :
class GlobalController extends GetxService {
  static GlobalController to = Get.put(GlobalController());

  final token = RxnString(null);
  final sn = RxnString(null);

  @override
  void onInit() {
    super.onInit();
    initDeviceId();
    token.value = SPUtil.instance.get('token');
  }

  void updateToken(String t) {
    token.value = t;
    SPUtil.instance.put('token', t);
  }

  void updateSn(String sn) {
    this.sn.value = sn;
    SPUtil.instance.put(SPKey.sn, sn);
    HttpUrl.httpHeader[SPKey.sn] = sn;
  }

  Future<void> initDeviceId() async {
    String deviceId = "";
    final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
    try {

      if (Platform.isAndroid) {
        AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
        deviceId = androidInfo.id; // Android
        androidInfo.version;
        print(
            '===========getDeviceId build.serialNumber: ${androidInfo.serialNumber} ===${androidInfo.id} ==aversion:${androidInfo.version.release}');
        SPUtil.instance.put(SPKey.androidVersion, androidInfo.version.release);
      } else if (Platform.isIOS) {
        IosDeviceInfo iosDeviceInfo = await deviceInfoPlugin.iosInfo;
        deviceId = iosDeviceInfo.identifierForVendor!; // iOS
        print('===========getDeviceId build.serialNumber: $iosDeviceInfo  ');
      }
    } catch (e) {
      print('Failed to get device id: $e');
    }
    print('===========getDeviceId deviceId: $deviceId');
    if (deviceId.isNotEmpty) {
      // SPUtil.instance.put(SPKey.sn, deviceId);
      updateSn(deviceId);
    }
  }

  void logout() {
    token.value = null;
    SPUtil.instance.clearAll();
    SPUtil.instance.put(SPKey.sn, sn.value);
    Get.offAllNamed(AppRoutes.login);
  }
}
